/**
 * Created by ljg on 2017/2/22.
 */
export default function () {
    angular.module('ui.form')
        .directive('uiFormSelectRemote', function (ajaxHelper) {
            return {
                restrict: 'E',
                replace: true,
                transclude: true,
                controller:function ($scope,$attrs) {
                    ajaxHelper.getJson($attrs.url,function (result) {
                        const dataList=result.data||[];
                        const valueName=$attrs.valueName||'code';
                        const textName=$attrs.textName||'name';
                        const options=[{code:"",name:"请选择"}];
                        dataList.map(data=>{
                            const op={};
                            op.code=data[valueName];
                            op.name=data[textName];
                            options.push(op);
                        });
                        $scope.dataOptions=options;
                        $scope.$apply();
                        $($attrs.$$element).find('select').val($attrs.value);

                    })
                },
                require:"^?uiForm",
                scope:{
                    value:'@' //自动绑定，传递的是字符串
                },
                template: function(el,attr){
                    return '<div class={{ngClass}}> ' +
                        '<div class={{"col-md-"+cols}}>' +
                        '<label class="control-label">'+attr.label+'</label>' +
                        '</div>'+
                        '<div class="col-md-6">' +
                        '<select class="form-control" name='+attr.name+'>' +
                            '<option ng-repeat="op in dataOptions" value={{op.code}}>{{op.name}}</option>'+
                        '</select> ' +
                        '</div>'+
                        '</div>';
                },
                link : function(scope, element, attrs,ctrl) {

                    const result=['has-success','has-error','has-success'];
                    const cols=ctrl._spliceColumn()||2;
                    scope.ngClass="form-group col-md-"+12/cols;
                    scope.cols=parseInt(cols)+1;

                    scope.$on("ngValueReset",function (event) {
                        $(element).find("select").val(scope.value);
                    });

                    scope.$watch('value',function (newValue,oldValue) {
                        $(element).find("select").val(newValue);
                    });
                },
            };
        });
}